package crmdna.payment;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import crmdna.common.APIResponse;
import crmdna.common.Utils;

@SuppressWarnings("serial")
public class PaypalDoExpressCheckoutServlet extends HttpServlet {

	public void doOptions(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// TODO: make sure we only accept request from paypal
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Allow-Methods", "POST");
		resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
		resp.setHeader("Access-Control-Max-Age", "86400");
		resp.setHeader("Allow", "POST, OPTIONS");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		try {

			resp.setHeader("Access-Control-Allow-Origin", "*");

			String token = req.getParameter("token");
			String payerId = req.getParameter("PayerID");
			String rootUrl = req.getServerName();

			TokenProp tokenProp = Token.safeGet(token);

			String redirectUrl = Payment.doExpressCheckout(token, payerId,
					tokenProp.paypalLogin, tokenProp.paypalPwd,
					tokenProp.paypalSecret, rootUrl, tokenProp.sandbox);

			// Payment.doExpressCheckout should not throw any exception

			resp.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
			Utils.ensureValidUrl(redirectUrl);
			resp.setHeader("Location", redirectUrl);

		} catch (Exception ex) {
			// just in case
			APIResponse apiResponse = new APIResponse(ex);
			String errMessage = "Error in Paypal DoExpressCheckout. Error code: "
					+ apiResponse.statusCode
					+ "\nMessage: "
					+ apiResponse.userFriendlyMessage
					+ "\n\nStack trace: "
					+ apiResponse.object;
			Logger logger = Logger
					.getLogger(PaypalDoExpressCheckoutServlet.class.getName());
			logger.severe(errMessage);

			resp.getWriter().println(errMessage);
		}
	}
}